import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'

import { LOGIN_PAGE, NOT_FOUND_PAGE, ROOT_PAGE, AUTH_LOGIN_PAGE } from './routes/index'
import { setupRouterGuard } from './guard'
import { resetRoutePath } from "@/router/util";
import microApp from "@micro-zoe/micro-app";

const basicRoutes: Array<RouteRecordRaw> = [LOGIN_PAGE, ROOT_PAGE, NOT_FOUND_PAGE, AUTH_LOGIN_PAGE]
const BASIC_NAME_LIST: string[] = []
const getRouteNames = (array: any[]) =>
    array.forEach(item => {
        BASIC_NAME_LIST.push(item.name)
        getRouteNames(item.children || [])
    })
getRouteNames(basicRoutes)

// 根据打开的域名重置route
resetRoutePath(basicRoutes);

const router = createRouter({
    history: createWebHistory(),
    routes: basicRoutes as unknown as RouteRecordRaw[],
    strict: true,
    scrollBehavior: () => ({ left: 0, top: 0 })
})

// reset router
export function resetRouter() {
    router.getRoutes().forEach(route => {
        const { name } = route
        if (name && !BASIC_NAME_LIST.includes(name as string)) {
            router.hasRoute(name) && router.removeRoute(name)
        }
    })
}

// config router 1
export function setupRouter(app: App<Element>) {
    setupRouterGuard(router)
    // 注册主应用路由
    microApp.router.setBaseAppRouter(router);
    app.use(router)
}

export default router
